package breeze.pixel.weather.cityhistory.model;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import brz.breeze.tool_utils.Blog;

public class MyDatabaseUtils {

    private static final String TAG="MyDatabaseUtils";

    @SuppressLint("StaticFieldLeak")
    private static MyDatabaseUtils utils;

    @SuppressLint("StaticFieldLeak")
    private static Context mContext;

    private static MyDatabaseHelper helper;

    private static SQLiteDatabase db;

    public MyDatabaseUtils(Context context){
        if(helper==null){
            helper = new MyDatabaseHelper(context, "Citys.db", null, 1);
            helper.getWritableDatabase();
            db = helper.getWritableDatabase();
        }
        mContext=context;
    }

    public static MyDatabaseUtils getInstance(Context context){
        if(utils==null){
            utils=new MyDatabaseUtils(context);
        }
        return utils;
    }

    public void addData(String cityName,String cityID){
        if(!getIsExiseData(cityID)){
            ContentValues value = new ContentValues();
            value.put("Name", cityName);
            value.put("ID", cityID);
            db.insert("Citys", null, value);
            Blog.i(TAG,"数据库添加数据："+cityName+cityID);
            value.clear();
        }
    }

    public void deleteData(String cityID){
        if(getIsExiseData(cityID)){
            db.delete("Citys", "ID = ?", new String[]{cityID});
            Blog.i(TAG,"数据库删除数据："+cityID);
        }
    }

    public void deleteAll(){
        db.delete("Citys","ID != ?", new String[]{""});
        Blog.i(TAG,"数据库清空数据");
    }

    public List<CityInfo> getAllData(){
        @SuppressLint("Recycle")
        Cursor cursor=db.query("Citys", null, null, null, null, null, null);
        List<CityInfo> datas = new ArrayList<CityInfo>();
        if(cursor.moveToFirst()){
            do{
                String name=cursor.getString(cursor.getColumnIndex("Name"));
                String id=cursor.getString(cursor.getColumnIndex("ID"));
                CityInfo info = new CityInfo();
                info.setCityID(id);
                info.setCityName(name);
                datas.add(info);
            }while(cursor.moveToNext());
        }
        return datas;
    }

    public boolean getIsExiseData(String id){
        boolean isExise = false;
        @SuppressLint("Recycle")
        Cursor cursor = db.query("Citys", new String[]{"ID"}, "ID = ?", new String[]{id}, null, null, null);
        if(cursor.moveToFirst()){
            do{
                String id2 = cursor.getString(cursor.getColumnIndex("ID"));
                if(id.equalsIgnoreCase(id2)){
                    isExise = true;
                }
            }while(cursor.moveToNext());
        }
        return isExise;
    }
}
